<template>
  <div class="statistics-container">
    <h1>统计分析</h1>
    <el-row :gutter="20" align="middle" class="toolbar">
      <el-col :span="6">
        <el-date-picker
          v-model="selectedYear"
          type="year"
          placeholder="选择年份"
          @change="onYearOrMonthChange"
        />
      </el-col>
      <el-col :span="6">
        <el-select v-model="selectedMonth" placeholder="选择月份" @change="onYearOrMonthChange" style="width: 100%">
          <el-option label="全部" :value="null" />
          <el-option v-for="m in 12" :key="m" :label="m + '月'" :value="m" />
        </el-select>
      </el-col>
      <el-col :span="6" v-if="isDailyView">
        <el-button type="primary" @click="backToMonthly">返回月视图</el-button>
      </el-col>
    </el-row>
    <div style="display: flex; gap: 20px;">
      <div style="width: 50%">
        <div class="chart-title">{{ chartOrderTitle }}</div>
        <div ref="chartOrderRef" class="chart" style="height: 400px; width: 100%"></div>
      </div>
      <div style="width: 50%">
        <div class="chart-title">{{ chartAmountTitle }}</div>
        <div ref="chartAmountRef" class="chart" style="height: 400px; width: 100%"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, computed } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import axios from '../utils/request';
import baseURL from '../config/baseURL';

const selectedYear = ref(new Date());
const selectedMonth = ref(null);
const isDailyView = ref(false);
const chartOrderRef = ref(null);
const chartAmountRef = ref(null);
let chartOrderInstance = null;
let chartAmountInstance = null;

const monthlyData = ref([]);
const dailyData = ref([]);

const getYear = () => selectedYear.value instanceof Date
  ? selectedYear.value.getFullYear()
  : Number(selectedYear.value);

const fetchMonthlyData = async () => {
  try {
    const res = await axios.get(`/api/order/monthly`, { params: { year: getYear() } });
    if (res.data.code === 1) {
      monthlyData.value = res.data.data;
      renderCharts();
    } else {
      ElMessage.error(res.data.message || '获取月数据失败');
    }
  } catch (e) {
    ElMessage.error('网络错误');
  }
};

const fetchDailyData = async (month) => {
  try {
      const res = await axios.get(`/api/order/daily`, { params: { year: getYear(), month } });
    if (res.data.code === 1) {
      dailyData.value = res.data.data;
      renderCharts();
    } else {
      ElMessage.error(res.data.message || '获取日数据失败');
    }
  } catch (e) {
    ElMessage.error('网络错误');
  }
};

const onYearOrMonthChange = () => {
  if (selectedMonth.value) {
    fetchDailyData(selectedMonth.value);
  } else {
    fetchMonthlyData();
  }
};

const backToMonthly = () => {
  isDailyView.value = false;
  selectedMonth.value = null;
  fetchMonthlyData();
};

const getChartData = () => {
  let xData = [];
  let orderCountData = [];
  let totalAmountData = [];
  if (selectedMonth.value) {
    xData = dailyData.value.map(item => item.day + '日');
    orderCountData = dailyData.value.map(item => item.orderCount);
    totalAmountData = dailyData.value.map(item => item.totalAmount);
  } else {
    xData = monthlyData.value.map(item => item.month + '月');
    orderCountData = monthlyData.value.map(item => item.orderCount);
    totalAmountData = monthlyData.value.map(item => item.totalAmount);
  }
  return { xData, orderCountData, totalAmountData };
};

const renderCharts = () => {
  nextTick(() => {
    if (!chartOrderInstance) {
      chartOrderInstance = echarts.init(chartOrderRef.value);
    }
    if (!chartAmountInstance) {
      chartAmountInstance = echarts.init(chartAmountRef.value);
    }
    const { xData, orderCountData, totalAmountData } = getChartData();

    // 订单数图表
    chartOrderInstance.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: function(params) {
          const idx = params[0].dataIndex;
          const amount = totalAmountData[idx] !== undefined ? totalAmountData[idx] : '-';
          return `${params[0].axisValue}<br/>订单数: ${orderCountData[idx]}<br/>销售额: ${amount}`;
        }
      },
      xAxis: { type: 'category', data: xData },
      yAxis: { type: 'value' },
      series: [
        {
          name: '订单数',
          type: 'line',
          data: orderCountData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: { width: 3 },
        },
      ],
    });
    // 销售额图表
    chartAmountInstance.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: function(params) {
          const idx = params[0].dataIndex;
          const order = orderCountData[idx] !== undefined ? orderCountData[idx] : '-';
          return `${params[0].axisValue}<br/>订单数: ${order}<br/>销售额: ${totalAmountData[idx]}`;
        }
      },
      xAxis: { type: 'category', data: xData },
      yAxis: { type: 'value' },
      series: [
        {
          name: '销售额',
          type: 'line',
          data: totalAmountData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: { width: 3 },
        },
      ],
    });
    // 图表联动
    echarts.connect([chartOrderInstance, chartAmountInstance]);
  });
};

const getTitle = (type) => {
  const year = getYear();
  const month = selectedMonth.value;
  if (month) {
    return `${year}年${month}月的${type}`;
  } else {
    return `${year}年的${type}`;
  }
};
const chartOrderTitle = computed(() => getTitle('订单数'));
const chartAmountTitle = computed(() => getTitle('销售额'));

onMounted(() => {
  fetchMonthlyData();
});
</script>

<style scoped>
.statistics-container {
  padding: 24px;
}
.toolbar {
  margin-bottom: 24px;
}
.chart {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  padding: 16px;
}
.chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
</style> 